<template>
	<div>
		<el-breadcrumb separator="/">
			<el-breadcrumb-item><i class="el-icon-s-home" style="margin-right: 15px;font-size: 16px"></i>试验设备</el-breadcrumb-item>
    </el-breadcrumb>
		<div class="info">
			<el-card shadow="always">
				<div slot="header">
					<el-form :model="equipInfoForm" ref="equipInfoForm" label-width="90px" size="small">
						<el-row>
							<el-col :span="8">
								<el-form-item label="有效日期">
									<el-date-picker v-model="equipInfoForm.timeSelect" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="pickerOptions" value-format="yyyy-MM-dd" style="width:100%"></el-date-picker>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="设备型号">
									<el-input placeholder="请输入设备型号" v-model="equipInfoForm.equipmModel" clearable style="width:100%"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="工位名称">
									<el-select v-model="equipInfoForm.workePosit" placeholder="请选择工位名称" style="width:100%" clearable>
										<el-option v-for="item in stationInfo" :key="item.station_id" :label="item.station_name" :value="item.station_id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="8">
								<el-form-item label="设备名称">
									<el-input placeholder="请输入设备名称" v-model="equipInfoForm.equipmName" clearable style="width:100%"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8">
								<el-form-item label="设备编号">
									<el-input placeholder="请输入设备编号" v-model="equipInfoForm.equipmNumber" clearable style="width:100%"></el-input>
								</el-form-item>
							</el-col>
							<el-col :span="8" >
								<div style="float: right;">
									<el-button type="primary" size="small" @click="getRecordList">查询</el-button>
									<el-button size="small" class="textBtn" @click="resetInfor">重置</el-button>
								</div>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<div>
					<div style="float: right;"><el-button type="text" class="global_add" @click="addEquipment" :disabled="btnList.addEqu" style="width:140px;margin-left: 15px">+&nbsp;新增设备</el-button>
						<el-dropdown @command="exportDeviceInfo">
							<el-button type="text" class="global_add" :disabled="btnList.export" style="width:120px;">导出设备<i class="el-icon-arrow-down el-icon--right"></i></el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item :disabled="btnList.export" command="selection">导出选中</el-dropdown-item>
								<el-dropdown-item :disabled="btnList.export" command="allInfo">导出全部</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown></div>
				</div>
				<el-table v-loading="dataLoading" :data="equipRecordData.slice((currentPage-1)*pagesize,currentPage*pagesize)" row-key="instr_id" stripe ref="equipRecordData"  @sort-change='sortChange' @selection-change="selectionChange" style="width: 100%;margin-top:10px">
					<el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
          <el-table-column prop="instr_name" label="设备名称" show-overflow-tooltip></el-table-column>
					<el-table-column prop="model" label="设备型号" show-overflow-tooltip></el-table-column>
					<el-table-column prop="spec" label="设备规格" show-overflow-tooltip></el-table-column>
					<el-table-column prop="instr_number" label="设备编号" sortable='custom' show-overflow-tooltip></el-table-column>
					<el-table-column prop="station_name" label="工位名称" sortable='custom'></el-table-column>
					<el-table-column label="有效日期" prop="exp_date" sortable='custom'>
						<template slot-scope="scope">
							<div :style="{'color':(scope.row.dateCount < 0 ?'#D9001B':'#000000')}">{{scope.row.exp_date}}</div>
            </template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<el-button type="text" :disabled="btnList.view" @click="viewInfo(scope.$index, scope.row)" class="global_edit" size="small">查看</el-button>
							<el-button type="text" :disabled="btnList.edit" @click="editInfo(scope.$index, scope.row)" class="global_edit" style="color: #5344AA;" size="small">编辑</el-button>
							<el-button v-if="scope.row.dateCount < 30" type="text" :disabled="btnList.edit" @click="checkInfo(scope.$index, scope.row)" class="global_edit" style="color: #008080;" size="small">检定</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination class="pagination" background :hide-on-single-page="showPagination" :current-page.sync="currentPage" @size-change="handleSizeChange" :page-size="pagesize" layout="prev, pager, next" :total="equipRecordData.length"></el-pagination>
			</el-card>
			<el-dialog title="更新设备有效日期" :visible.sync="checkVisible" width="30%">
				<el-form :model="checkInfoForm" :rules="checkInfoFormRules" ref="checkInfoForm" label-width="80px" size="small" style="margin: 10px 0 0 20px">
					<el-form-item label="有效日期" prop="indate">
						<el-date-picker v-model="checkInfoForm.indate" clearable :picker-options="checkOptions" type="date" placeholder="选择日期" style="width:50%" value-format="yyyy-MM-dd"></el-date-picker>
					</el-form-item>
				</el-form>
        <span slot="footer" class="dialog-footer">
        <el-button @click="checkVisible = false;checkInfoForm.indate=''">取消</el-button>
        <el-button type="primary" @click="updateIndate">保存</el-button></span>
      </el-dialog>
		</div>
	</div>
</template>

<script>
import { serverURL } from '../../public/setting';
import sessionStorage from '../../public/storage.js';
import roleBtn from '../../public/means.js';
export default {
	data() {
		return {
			checkVisible: false,
			btnList: {
				addEqu: false, // 新增设备按钮
				export: false, // 导出设备按钮
				view: false, // 查看
				edit: false, // 编辑和检定
      },
      menuId: 16,
			checkInfoForm: { // 检定中更新设备有效日期表单
				indate: ''
			},
			equipInfoForm: {
				equipmNumber: '', // 设备编号
				equipmName: '', // 设备名称
				equipmModel: '', // 设备型号
				workePosit: '', // 工位名称
      	timeSelect: '',	// 时间选择
			},
			stationInfo: [], // 工位名称下拉列表
			dataLoading: false,	// 数据加载
      equipRecordData: [], // 试验设备列表
			showPagination: true,
			currentPage: 1,
      pagesize: 10,
			multSelect: [], // 多选数据
			pickerOptions: { // 时间范围快捷选择
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
					}, {
						text: '最近一个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
							picker.$emit('pick', [start, end]);
						}
					}, {
						text: '最近三个月',
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
							picker.$emit('pick', [start, end]);
						}
				}]
			},
			checkOptions:{ // 更新设备有效日期中当前日期之前的不可选择
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
			checkInfoFormRules:{
				indate: [
					{ required: true, message: '该选项为必填项', trigger: 'change' }
        ]
			}
		};
	},
	methods: {
		/**
		 * @brief 表格数据根据具体某一列进行排序
		 * @param attr 传入要排序的列
		 * @param rev 排列顺序：升序true 降序false
		 * @return 小于-1 大于1 等于0
		 */
		generalSort(attr, rev){
			console.info(attr, rev)
			if (rev == undefined) { // 未传入排列顺序默认升序
				rev = 1;
			} else { // 升序true 降序false
				rev = (rev) ? 1 : -1;
			}
			return function (arry, barry) {
				arry = arry[attr]; // 取对象里key对应的value值
				barry = barry[attr];
				if (arry < barry) {
					return rev * -1;
				}
				if (arry > barry) {
					return rev * 1;
				}
				return 0;
			}
		},
		// 表格排序问题
		sortChange(column){
			this.currentPage = 1;
			// sort对数组的元素进行排序，每次比较两个值
			if (column.prop === 'exp_date') {
				this.equipRecordData = this.equipRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			} else if (column.prop === 'instr_number') {
				this.equipRecordData = this.equipRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			}else if (column.prop === 'station_name') {
				this.equipRecordData = this.equipRecordData.sort(this.generalSort(column.prop, column.order === 'ascending'));
			}
			this.equipRecordData = this.equipRecordData.slice(0, this.pageSize) // 排序完显示到第一页
		},
		handleSizeChange(val) {
      this.pagesize=val;
		},
		//  多选
		selectionChange (val) {
			this.multSelect = val;
		},
		//	导出设备信息，command：导出全部or导出选中
		async exportDeviceInfo(command) {
			let params;
			if (command === 'selection') { // 导出选中
				if (this.multSelect.length === 0) {
          this.$message.error('请勾选需要导出的数据！');
          return
        }
				params = {
					equipInfo: this.multSelect
				}
			} else { // 导出全部
				params = {
					equipInfo: this.equipRecordData
				}
			}
			this.$message({ message: '正在导出设备信息，请稍后...', type: 'success', duration: 1000 });
			const ret = await this.$http.post("/equipManagement/exportDeviceInfo",params);
			if(ret.code === 200){
				let url = serverURL + '/public/deviceInfoReport/' + ret.result;
				location.href = url
				this.$message({ message: '导出设备信息成功!', type: 'success', duration: 1000 });
      }
		},
		// 点击表格行检点按钮弹出检定框
		checkInfo(index,row){
			this.checkVisible = true;
			this.instrumentId = row.instr_id;
		},
		// 更新设备有效期
		async updateIndate() {
			this.$message({ message: '正在更新有效期，请稍等!', type: 'success', duration: 1000 });
			const params = {
				checkData: this.checkInfoForm.indate,
				instrumentId: this.instrumentId
			}
			const ret = await this.$http.post("/equipManagement/updateIndate",params);
			if (ret.code === 200) {
				this.checkVisible = false;
				this.checkInfoForm.indate='';
				this.getRecordList();
			}
		},
		// 点击表格编辑按钮进行页面跳转
		editInfo(index, row){
			this.$router.push({
				path: '/AddEquipment',
				query:{
					sign: 'edit',
					expDate: row.exp_date, // 有效日期
					instrName: row.instr_name, // 设备名称
					instrNumber: row.instr_number, // 设备编号
					model: row.model, // 设备型号
					spec: row.spec, // 设备规格
					equipKind: row.kind_name, // 设备类型中文
					equipKindId: row.instr_kind, // 设备类型uuid
					stationId: row.station_id, // 工位id
					stationName: row.station_name, // 工位名称
					instrId: row.instr_id, // 设备uuid
					ifCheck: row.if_check.toString(), // 是否点检
					equipPurpose: row.instr_use.toString(), // 是否有效
				}
			})
		},
    //  重置筛选条件信息
    resetInfor(){
      this.equipInfoForm.equipmNumber ='';
      this.equipInfoForm.equipmName ='';
      this.equipInfoForm.equipmModel = '';
      this.equipInfoForm.workePosit = '';
      this.equipInfoForm.timeSelect = '';
      this.getRecordList();
    },
		//获取试验设备表格数据
		async getRecordList(){
			this.dataLoading = true;
			if(this.equipInfoForm.timeSelect === null){
        this.equipInfoForm.timeSelect = '';
      }
			let params = {
				userId:JSON.parse(sessionStorage.getItem('userInfo')).user_id,
				startTime: this.equipInfoForm.timeSelect[0],
        endTime: this.equipInfoForm.timeSelect[1],
				'equipmNumber': this.equipInfoForm.equipmNumber,
				'equipmName': this.equipInfoForm.equipmName,
        'equipmModel': this.equipInfoForm.equipmModel,
        'workePosit': this.equipInfoForm.workePosit,
				sign: 'all'
			}
			if (this.$route.query.sign !== undefined) { // 如果从首页跳转过来显示的数据
				params.sign = 'test';
			}
			const ret = await this.$http.get("/equipManagement/getRecordList",{params,});
			this.equipRecordData = ret.result;
			this.dataLoading = false;
		},
    // 新增设备
    addEquipment(){
      this.$router.push({
				path: '/AddEquipment',
				query: {
					sign: 'add',
				}
			})
    },
		//查看点检信息
		viewInfo(index, row){
			this.$router.push({
				path: '/AddEquipment',
				query:{
					sign: 'view',
					expDate: row.exp_date,
					instrName: row.instr_name,
					instrNumber: row.instr_number,
					model: row.model,
					equipKind: row.kind_name,
					equipKindId: row.instr_kind,
					spec: row.spec,
					stationId: row.station_id,
					stationName: row.station_name,
					instrId: row.instr_id,
					ifCheck: row.if_check.toString(),
					equipPurpose: row.instr_use.toString()
				}
			})
		},
		//获取工位名称数据
		async getStationInfo(){
			const params = {
				userId:JSON.parse(sessionStorage.getItem('userInfo')).user_id
			}
			const ret = await this.$http.get("/equipManagement/getStationInfo",{params,});
			this.stationInfo = ret.result;
		},
		async roleBtnList () {
      const role_id = JSON.parse(sessionStorage.getItem('userInfo')).role_id;
      if(role_id){
        // 获取按钮权限状态
        let arr = await roleBtn.roleBtnList(role_id, this.menuId);
        this.btnList = arr;
      }
    }
	},
	created() {
    this.roleBtnList()
  },
	mounted() {
		this.getStationInfo();
    this.getRecordList();
	}
};
</script>
<style lang="scss" scoped>
@import "./EquipmentManagement.scss";
</style>